<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="支付订单"
        left-arrow
        @click-left="back"
      />
    </header>
    <div class="content">
      <p>共有{{ totalNum }}件商品</p>
      <van-image :src="imgurl" />
      <p>总计{{ totalPrice / 100 }}元人民币</p>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, Image as VanImage, Dialog } from 'vant'
import { getConfirmOrder, pay } from '@/api'
import { mapState } from 'vuex'
Vue.use(NavBar)
Vue.use(VanImage)
export default {
  // beforeRouteLeave (to, from, next) {
  //   if (this.payState) {
  //     next()
  //   } else {
  //     Toast('请先完成支付')
  //     next(false)
  //   }
  // },
  data () {
    return {
      imgurl: '',
      orderlist: [],
      payState: false
    }
  },
  methods: {
    back () {
      Dialog.confirm({
        message: '您可以在订单中心继续完成本次交易'
      }).then(() => {
        this.$router.go(-2)
      }).catch(() => {

      })
    }
  },
  computed: {
    ...mapState({
      userid: ({ user: { userid } }) => userid
    }),
    totalPrice () {
      return this.orderlist ? this.orderlist.reduce((sum, item) => {
        return sum + item.num * item.price
      }, 0) * 100 : 0
    },
    totalNum () {
      return this.orderlist ? this.orderlist.reduce((sum, item) => {
        return sum + item.num
      }, 0) : 0
    }
  },
  mounted () {
    getConfirmOrder({
      userid: this.userid,
      time: this.$route.params.time
    }).then(res => {
      this.orderlist = res.data.data
      pay({
        body: this.totalNum + '件商品',
        out_trade_no: this.$route.params.time,
        total_fee: this.totalPrice
      }).then(result => {
        this.imgurl = result.data.data
      })
    })
  }
}
</script>

<style lang="scss" scoped>
.content p{
  font-size: 20px;
}
</style>
